package com.enjoy.basic.serializable;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.LineBasedFrameDecoder;

import java.net.InetSocketAddress;

/**
 * Created by HP on 2019/7/15.
 */
public class ClientMsgPackEcho {
    private final String host;

    public ClientMsgPackEcho(String host) {
        this.host = host;
    }

    private void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            final Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, 9995))
                    .handler(new ChannelInitializerImp());
            ChannelFuture f = b.connect().sync();
            System.out.println("已经连接到服务器。。。。。。");
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }


    }

    private static class ChannelInitializerImp extends ChannelInitializer<Channel> {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            /*
           设置报文长度 避免粘报半包 穿个服务daunt
             */
            channel.pipeline().addLast("frameEncode", new LengthFieldPrepender((2)))//
                    //序列化
                    .addLast("msg_packEncode", new MsgPackEncode())
                    .addLast(new LineBasedFrameDecoder(1024))//分割服务端的报文 繁殖黏包
                    //产生实体类
                    .addLast(new MsgPackClientHandler(5));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ClientMsgPackEcho("127.0.0.1").start();
    }
}
